<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{CopyList, Peizhi, Exphone, ExphoneLog as ExphoneLogs, Config, Lists, Gsdselect, ExphoneCopy};
use think\Db;
use think\facade\Log;
use app\facade\Redis;
use think\facade\App;



class ExphoneLog extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('ExphoneLog')->setDescription('自动导入计划');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //日复制开关
        $copylists = (new CopyList())->where('status', 1)->select();
        foreach ($copylists as $copylist) {
            $pzs = $copylist['value'] ?? '';
            $pzs = json_decode($pzs, true) ?? [];
            $cfgpbpp = explode(',', $pzs['pbpp']) ?? [];
            $cfgpbpp = array_filter($cfgpbpp) ?? [];
            $province = explode(',', $pzs['provincelist']) ?? [];
            $province = array_filter($province) ?? [];
            $channel = explode(',', ($pzs['channellist'] ?? '')) ?? [];
            $channel = array_filter($channel) ?? [];
            $csdrstarttimes = (int)$pzs['datebefore'] ?? 20;
            $csdrendtimes = (int)$pzs['dateafter'] ?? 365;
            if ($csdrstarttimes > $csdrendtimes) {
                $csdrstarttimes = 20;
                $csdrendtimes = 365;
            }
            $csyouxiao = (int)$pzs['youxiao'] ?? 0;
            $cswuxiao = (int)$pzs['wuxiao'] ?? 0;
            if (!empty($pzs['daterangestar']) && !empty($pzs['daterangeend'])) {
                //判断结束日期
                if (date('Y-m-d') < $pzs['daterangestar'] && date('Y-m-d') < $pzs['daterangeend']) {
                    echo '跳过';
                    continue;
                } else if (date('Y-m-d') < $pzs['daterangestar'] || date('Y-m-d') >= $pzs['daterangeend']) {
                    echo '跳过';
                    continue;
                } else {
                    //判断今日已导入有效条数
                    $youxioahaves = (new ExphoneCopy())->where(['daorutime' => date('Y-m-d'), 'youxiao' => 1, 'copyid' => $copylist['id']])->count();
                    $yxlimit = (int)$csyouxiao ?? 0;
                    if ($youxioahaves >= $yxlimit) {
                        $yxlimit = 0;
                    } else {
                        $yxlimit = $yxlimit - $youxioahaves;
                    }
                    //判断今日还需导入无效数量
                    $wuxiaohaves = (new ExphoneCopy())->where(['daorutime' => date('Y-m-d'), 'youxiao' => 2, 'copyid' => $copylist['id']])->count();
                    $wxlimit = (int)$cswuxiao ?? 0;
                    if ($wuxiaohaves >= $wxlimit) {
                        $wxlimit = 0;
                    } else {
                        $wxlimit = $wxlimit - $wuxiaohaves;
                    }
                    if ($yxlimit > 0) {
                        $result = (new Exphone())
                            ->alias('ex')
                            ->leftJoin('exphone_copy ec', 'ex.phone = ec.phone')
                            ->where('ec.id', 'null')
                            ->where(['ex.typem' => $cfgpbpp])
                            ->where('ex.youxiao', 1)
                            ->where('ex.createTime', '<=', date('Y-m-d', time() - $csdrstarttimes * 86400))
                            ->where('ex.createTime', '>', date('Y-m-d', time() - $csdrendtimes * 86400));
                        if (count($province) > 0) {
                            $result = $result->where(['ex.province' => $province]);
                        }
                        if (count($channel) > 0) {
                            $result = $result->where(['ex.channel' => $channel]);
                        }
                        $result = $result->field('ex.*')
                            ->limit($yxlimit)
                            ->orderRaw('rand()')->select();
                    } else {
                        $result = [];
                    }
                    if ($wxlimit > 0) {
                        $result1 = (new Exphone())
                            ->alias('ex')
                            ->leftJoin('exphone_copy ec', 'ex.phone = ec.phone')
                            ->where('ec.id', 'null')
                            ->where(['ex.typem' => $cfgpbpp])
                            ->where('ex.youxiao', 2)
                            ->where('ex.createTime', '<=', date('Y-m-d', time() - $csdrstarttimes * 86400))
                            ->where('ex.createTime', '>', date('Y-m-d', time() - $csdrendtimes * 86400));
                        if (count($province) > 0) {
                            $result1 = $result->where(['ex.province' => $province]);
                        }
                        if (count($channel) > 0) {
                            $result = $result->where(['ex.channel' => $channel]);
                        }
                        $result1 = $result1->field('ex.*')
                            ->limit($wxlimit)
                            ->orderRaw('rand()')->select();
                    } else {
                        $result1 = [];
                    }
                    if (count($result) > 0) {
                        $result = $result->toArray();
                    } else {
                        $result = [];
                    }
                    if (count($result1) > 0) {
                        $result1 = $result1->toArray();
                    } else {
                        $result1 = [];
                    }
                    $resultarrr = array_merge($result, $result1);
                    $saves2 = [];
                    foreach ($resultarrr as $row) {
                        // $row['istype'] = $isphone['type'];
                        $row['daorutime'] = date('Y-m-d');
                        unset($row['id']);
                        $row['copyid'] = $copylist['id'];
                        $row['copy_name'] = $copylist['name'];
                        $saves2[] = $row;
                    }
                    Db::startTrans();
                    try {
                        (new ExphoneCopy())->saveAll($saves2);
                        Db::commit();
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                    }
                }
            }
        }

        (new Exphone())->whereNull('province')->chunk(100, function ($provincelist) {
            $save = [];
            foreach ($provincelist as $row) {
                $rdsnames = 'exphoneguishudis' . $row['id'];
                $rdspeizhi = Redis::get($rdsnames);
                if ($rdspeizhi) {
                    continue;
                }
                Redis::setex($rdsnames, 60, 60);
                $data = unserialize($row['ysdata']);
                $data['prefecture'] = explode('/', $data['prefecture']);
                $province = '';
                $city = '';
                if (count($data['prefecture']) == 3) {
                    $province = $data['prefecture'][1] ?? '';
                    $city = $data['prefecture'][2] ?? '';
                } else {
                    $subphone = substr(trim($row['phone']), 0, 7);
                    $subplist = (new Gsdselect())->where('phone', $subphone)->find();
                    if (!empty($subplist)) {
                        $province = $subplist['province'] ?? '';
                        $city = $subplist['city'] ?? '';
                    } else {
                        $getgsd = api_curlphone($row['phone']);
                        if (!empty($getgsd['data']['prov']) && !empty($getgsd['data']['city'])) {
                            $province = $getgsd['data']['prov'] ?? '';
                            $city = $getgsd['data']['city'] ?? '';
                        } elseif (!empty($getgsd['ret']) && $getgsd['ret'] == '40003') {
                            $province = '未知';
                            $city = '未知';
                        }
                    }
                }
                if (!empty($province) && !empty($city)) {
                    if ($province == '广西壮族自治区') {
                        $province = '广西';
                    }
                    if ($province == '西藏自治区') {
                        $province = '西藏';
                    }
                    if ($province == '宁夏回族自治区') {
                        $province = '宁夏';
                    }
                    if ($province == '新疆维吾尔自治区') {
                        $province = '新疆';
                    }
                    if ($province == '内蒙古自治区') {
                        $province = '内蒙古';
                    }
                    if ($province == '澳门特别行政区') {
                        $province = '澳门';
                    }
                    if ($province == '香港特别行政区') {
                        $province = '香港';
                    }
                    $province = str_replace('省', "", $province);
                    $city = str_replace('市', "", $city);
                    $save[] = ['province' => trim($province), 'city' => trim($city), 'id' => $row['id']];
                }
            }
            if (count($save) > 0) {
                (new Exphone())->allowfield(true)->saveAll($save);
            }
        });

        $exlist = (new ExphoneLogs())->where(['isrepeat' => 1, 'fenpei' => 1])->limit(20)->select();
        foreach ($exlist as $list) {
            $phone = (new Exphone())->where('id', $list['exId'])->find();
            if (empty($phone)) {
                (new ExphoneLogs())->where('id', $list['exId'])->update(['fenpei' => 3]);
                continue;
            }
            if (!empty($phone['phone']) && !preg_match("/^1[0-9]{10}$/", $phone['phone'])) {
                (new ExphoneLogs())->where('id', $list['exId'])->update(['fenpei' => 3]);
                continue;
            }
            $saves = [
                'laiyuan' => $data['laiyuan'] ?? '未知',
                'type' => $list['typem'] ?? 0,
                'pinpai' => (new Peizhi())->where('type', $list['typem'])->value('pinpai') ?? '',
                'name' => "未命名",
                'pingtai' => '字节-通投智选',
                'phone' =>  trim($phone['phone']) ?? "",
                'created' =>  date('Y-m-d H:i:s'),
                'createds' =>  date('Y-m-d H:i:s'),
                'address' => trim($phone['province']) . ' ' . trim($phone['city']),
                'isexcel' => 3,
                'allocation' => 1
            ];
            Db::startTrans();
            try {
                (new ExphoneLogs())->where('id', $list['id'])->update(['fenpei' => 2]);
                (new Lists())->allowfield(true)->save($saves);
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
            }
            $other = new \app\api\controller\Other();
            App::invokeMethod([$other, 'testAddCustomer']);
        }
        //走自动任务
        $list = (new Peizhi())->where('kags', 1)->select();
        $value = (new Config())->where('name', 'tags')->value('value') ?? '';
        $value = explode(',', $value) ?? [];
        // // 将数组转换为正则表达式
        $regexp = implode('|', array_map(function ($value) {
            return preg_quote($value, '/'); // 转义特殊字符
        }, $value));
        $laiyuan = (new Config())->where('name', 'laiyuan')->value('value') ?? '';
        $laiyuan = explode(',', $laiyuan) ?? [];
        if (count($laiyuan) <= 0) {
            dump('无来源不执行');
            die;
        }
        $drtime = (new Config())->where('name', 'drtime')->value('value') ?? '';
        $drtime = explode('-', $drtime) ?? [];
        $drstarttimes = (int)$drtime[0] ?? 20;
        $drendtimes = (int)$drtime[1] ?? 365;
        if ($drstarttimes <= 0 || $drstarttimes >= $drendtimes) {
            $drstarttimes = 20;
        }
        if ($drendtimes <= 0 || $drstarttimes >= $drendtimes) {
            $drendtimes = 365;
        }
        foreach ($list as $row) {
            if (!empty($row['daterangestar']) && !empty($row['daterangeend'])) {
                //判断结束日期
                if (date('Y-m-d') < $row['daterangestar'] && date('Y-m-d') < $row['daterangeend']) {
                    (new Peizhi())->where('id', $row['id'])->update(['kags' => 2]);
                }
                if (date('Y-m-d') < $row['daterangestar'] || date('Y-m-d') >= $row['daterangeend']) {
                    continue;
                }
            }
            if (!empty($row['datebefore']) && !empty($row['dateafter']) && $row['datebefore'] < $row['dateafter']) {
                $drstarttimes = (int)$row['datebefore'] ?? 20;
                $drendtimes = (int)$row['dateafter'] ?? 365;
            }
            $rdsnames = 'getexphonelog' . $row['id'];
            $rdspeizhi = Redis::get($rdsnames);
            if ($rdspeizhi) {
                dump('冷却时间');
                continue;
            }
            $youxiao = $row['youxiao'] ?? 0; //有效数量
            $wuxiao = $row['wuxiao'] ?? 0; //无效数量
            $startime = $row['startime'] ?? 0; //开始时间
            $endtime = $row['endtime'] ?? 0; //结束时间
            $times = $row['times'] ?? 1; //间隔分钟数
            $pbpp = $row['pbpp'] ?? ''; //屏蔽品牌
            $provincelist = $row['provincelist'] ?? ''; //跑动省份
            $nowtime = date('H');
            if ($nowtime < $startime || $nowtime >= $endtime) {
                dump('超过时间跳过');
                continue;
            }
            if (($youxiao + $wuxiao) <= 0) {
                dump('有效+无效为0跳过');
                continue;
            }
            //判断今天已经推送的有效和无效
            $todayyouxiao = (new ExphoneLogs())->where(['typem' => $row['type'], 'youxiao' => 1, 'isrepeat' => 1, 'date' => date('Y-m-d')])->count();
            $todaywuxiao = (new ExphoneLogs())->where(['typem' => $row['type'], 'youxiao' => 2, 'isrepeat' => 1, 'date' => date('Y-m-d')])->count();
            $rand = mt_rand(1, 10);
            if ($rand <= 7) {
                $ywxstatus = 1; //有效
            } else {
                $ywxstatus = 2; //无效
            }
            if ($ywxstatus == 1 && $todayyouxiao >= $youxiao && $todaywuxiao < $wuxiao) {
                $ywxstatus = 2; //无效
            }
            if ($ywxstatus == 2 && $todayyouxiao < $youxiao && $todaywuxiao >= $wuxiao) {
                $ywxstatus = 1; //无效
            }
            //有效超过就找无效
            if ($todayyouxiao >= $youxiao && $todaywuxiao >= $wuxiao) {
                dump('有效+无效都推送达标跳过');
                continue;
            }
            //查找要查找的品牌
            $pbpp = explode(',', $pbpp) ?? [];
            $typem = (new Peizhi());
            if (count($pbpp) > 0) {
                $typem = $typem->where('type', 'not in', $pbpp);
            }
            $typem = $typem->where('id', '<>', $row['id'])->where(['category' => $row['category']])->column('type');
            if (count($typem) <= 0) {
                dump('无查找品牌，跳过');
                continue;
            }
            $provincelist = explode(',', $provincelist) ?? [];
            $provincelist = array_filter($provincelist) ?? [];
            Redis::setex($rdsnames, $times * 60, 1);
            $result = $this->getlist($regexp, $laiyuan, $typem, $ywxstatus, $row, 0, $drstarttimes, $drendtimes, $provincelist);
            //如果返回false再跑一边状态相反的
            if (!$result) {
                if ($ywxstatus == 1 && $todaywuxiao < $wuxiao) {
                    $result = $this->getlist($regexp, $laiyuan, $typem, 2, $row, 0, $drstarttimes, $drendtimes, $provincelist);
                }
                if ($ywxstatus == 2 && $todayyouxiao < $youxiao) {
                    $result = $this->getlist($regexp, $laiyuan, $typem, 1, $row, 0, $drstarttimes, $drendtimes, $provincelist);
                }
            }
        }
    }

    //屏蔽标签  查找来源 查找品牌 配置参数
    public function getlist($regexp, $laiyuan, $typem, $ywxstatus, $peizhi, $cishu = 0, $drstarttimes = 20, $drendtimes = 365, $provincelist)
    {
        if ($cishu >= 5) {
            return true;
        }
        $result = (new Exphone())
            ->alias('ex')
            ->leftJoin('exphone_log el', 'ex.id = el.exId')
            ->where('el.exId', 'null')
            ->where('ex.yxtags', 'NOT REGEXP', $regexp)
            ->where(['ex.channel' => $laiyuan, 'ex.typem' => $typem, 'ex.youxiao' => $ywxstatus])
            ->orderRaw('rand()')
            ->field('ex.id,ex.phone')
            ->where('ex.createTime', '<=', date('Y-m-d', time() - $drstarttimes * 86400))
            ->where('ex.createTime', '>', date('Y-m-d', time() - $drendtimes * 86400));
        if (count($provincelist) > 0) {
            $result = $result->where(['ex.province' => $provincelist]);
        }
        $result = $result->find();
        //查重
        if (!empty($result)) {
            //进行查询
            $ccdata = [
                "mobile" => $result['phone'],
                "maxNumsPreMobile" => 0
            ];
            $ccjsonData = json_encode($ccdata);
            // 2. 请求服务器处理
            $ccurl = "https://open.workec.com/v2/customer/queryExist";
            $cishu += 1;
            list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
            $ccrjson = json_decode($ccreturnContent, true) ?? [];
            $isrepeat = 1;
            if (!empty($ccrjson['data']) && count($ccrjson['data']) > 0 && !empty($ccrjson['data'][0]['num'])) {
                $isrepeat = 2;
            }
            $res = (new ExphoneLogs())->allowfield(true)->save(['date' => date('Y-m-d'), 'typem' => $peizhi['type'], 'exId' => $result['id'], 'youxiao' => $ywxstatus, 'isrepeat' => $isrepeat]);
            if ($res) {
                if ($isrepeat == 2) {
                    $this->getlist($regexp, $laiyuan, $typem, $ywxstatus, $peizhi, $cishu, $drstarttimes, $drendtimes, $provincelist);
                }
                return true;
            }
            return false;
        } else {
            return false;
        }
    }
}
